package com.dunshan.member.config;


import brave.Span;
import brave.Tracer;
import brave.baggage.BaggageField;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import java.io.IOException;

/**
 * @author dunshan
 * @program: dunshan-pef
 * @description:
 * @date 2021-10-03 17:45:30
 */
@Log4j2
@Component
public class ContextFilter implements Filter {

    private final Tracer tracer;

    ContextFilter(Tracer tracer) {
        this.tracer = tracer;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        BaggageField dunshan = BaggageField.getByName("dunshan");
        String flag = dunshan.getValue();
        Span currentSpan = this.tracer.currentSpan();
        AppContext appContext = new AppContext();
        if (StringUtils.isNotBlank(flag)) {
//            log.info("压测流量: " + flag);
            currentSpan.tag("flag", flag);
            appContext.setTraceId(flag);
            AppContext.setContext(appContext);
        } else {
//            log.info("正常流量: " + flag);
            AppContext.setContext(appContext);
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        AppContext.removeContext();
        Filter.super.destroy();
    }
}
